<template>
	<view class="container">

		<view class="">
			<u-subsection fontSize="14px" :list="list" :current="curNow" @change="sectionChange" bgColor="#3c9cff">
			</u-subsection>
		</view>

		<view>
			<u--form labelPosition="top" :model="setMeal" :rules="rules" ref="uForm">

				<u-form-item label="套餐名称" prop="name" borderBottom labelWidth="200px">
					<u--input v-model="setMeal.name" border="none"></u--input>
				</u-form-item>

				<u-form-item label="开始时间" prop="params.beginTime" borderBottom labelWidth="200px"
					@click="openDatetimePicker">
					<u--input v-model="setMeal.params.beginTime" border="none"></u--input>
				</u-form-item>

				<u-form-item label="结束时间" prop="params.endTime" borderBottom labelWidth="200px"
					@click="openDatetimePicker2">
					<u--input v-model="setMeal.params.endTime" border="none"></u--input>
				</u-form-item>

				<buuug7-simple-datetime-picker ref="myPicker" @submit="createTimeStart" :start-year="2023"
					:end-year="2099" :time-init="1688860800000" :time-hide="[true, true, true, false, false, false]"
					:time-label="['年', '月', '日', '时', '分', '秒']" />

				<buuug7-simple-datetime-picker ref="myPicker2" @submit="createTimeEnd" :start-year="2023"
					:end-year="2099" :time-init="1688860800000" :time-hide="[true, true, true, false, false, false]"
					:time-label="['年', '月', '日', '时', '分', '秒']" />

				<u-button type="primary" @click="getPageList(1)">查询</u-button>
			</u--form>
		</view>

		<view v-if="dataLists.length > 0">
			<u-list @scrolltolower="scrolltolower" class="u-list">
				<u-list-item v-for="(item, index) in dataLists" :key="index">
					<view class="box">
						<u--form labelPosition="left" :model="item" :rules="rules">



							<u-form-item label="id" prop="id" borderBottom labelWidth="120px">
								<u--input v-model="item.id" border="none" disabled></u--input>
							</u-form-item>
							<u-form-item label="套餐名称" prop="name" borderBottom labelWidth="120px">
								<u--input v-model="item.name" border="none" disabled></u--input>
							</u-form-item>


							<u-form-item label="日封顶价" prop="dayTopPay" borderBottom labelWidth="120px">
								<u--input v-model="item.dayTopPay" border="none"></u--input>
							</u-form-item>

							<u-form-item label="总费用" prop="totalPay" borderBottom labelWidth="120px">
								<u--input v-model="item.totalPay" border="none"></u--input>
							</u-form-item>


							<view class="myMeal1">
								<view class="" style="width:40%;">
									<u-form-item label="起步价:" prop="startTime" labelWidth="55px">
										<u--input maxlength="2" v-model="item.startTime" border="none"></u--input>
									</u-form-item>
								</view>

								<view class="" style="width:40%;">
									<u-form-item label="小时,共" prop="startTotalPay" labelWidth="55px">
										<u--input maxlength="2" v-model="item.startTotalPay" border="none"></u--input>
									</u-form-item>
								</view>

								<view class="">
									<u-form-item label="元">
									</u-form-item>
								</view>
							</view>

							<view class="myMeal1">
								<view class="" style="width:40%;">
									<u-form-item label="递增价:" prop="incrementTime" borderBottom labelWidth="55px">
										<u--input maxlength="2" v-model="item.incrementTime" border="none"></u--input>
									</u-form-item>
								</view>

								<view class="" style="width:40%;">
									<u-form-item label="每小时" prop="incrementPay" borderBottom labelWidth="55px">
										<u--input maxlength="2" v-model="item.incrementPay" border="none"></u--input>
									</u-form-item>
								</view>

								<view class="">
									<u-form-item label="元">
									</u-form-item>
								</view>
							</view>


							<u-form-item label="创建时间" prop="createTime" borderBottom labelWidth="120px">
								<u--input v-model="item.createTime" border="none" disabled></u--input>
							</u-form-item>



							<u-form-item label="是否启用" prop="status" borderBottom labelWidth="120px">
								<u-switch v-model="item.status" @change="switchChange(item)" activeValue="0"
									inactiveValue="1"></u-switch>
							</u-form-item>


							<view class="updateMessage" v-if="checkRole(['admin'])">
								<view class="mybuttom">
									<u-button type="primary" size="mini" @click="myUptate(item)">修改</u-button>
								</view>
								<view class="mybuttom">
									<u-button type="error" size="mini" @click="myDelete(item)">删除</u-button>
								</view>
							</view>
						</u--form>
					</view>
				</u-list-item>
			</u-list>

			<view style="display: flex; justify-content: center; margin-bottom: 20px; margin-top: 10px;">
				<view v-if="setMeal.pageTotal > setMeal.pageNum ">
					下拉加载更多...
				</view>
				<view class="" v-else>没有更多数据..</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		validateDate
	} from '@/utils/common';
	import {
		checkPermi,
		checkRole
	} from "@/utils/permission"; // 权限判断函数
	import {
		listMeal,
		getMeal,
		delMeal,
		addMeal,
		updateMeal
	} from "@/api/system/setmeal";
	export default {

		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		
		onLoad(e){
			console.log('从商户修改页跳转过来的'+JSON.stringify(e))
			if(e.userId){
				this.setMeal.name = e.userId;
				this.setMeal.status = '';
				this.getPageList(1);
			}
			
		},
		

		data() {
			return {
				setMealList: [],
				merchantNameList: [],
				list: ['添加套餐', '查找套餐'],
				curNow: 1,
				dataLists: [],
				setMeal: {
					name: '',
					dayTopPay: '',
					totalPay: '',
					startTime: '',
					startTotalPay: '',
					incrementTime: '',
					incrementPay: '',
					status:0,
					
			
					createTimeStart: '',
					createTimeEnd: '',
					pageNum: 1,
					pageSize: 5,
					params: {
						"beginTime": '',
						'endTime': ''
					},
					pageTotal: 1,
				},

			}
		},
		methods: {
			switchChange: function(item) {
				uni.showModal({
					content: item.status === '0' ? '确定要启动吗' : '确定要删除吗',
					success: (res) => {
						if (res.confirm) {
							//console.log("用户点了确定")
						} else {
							console.log("用户点了取消" + item.status)
							if (item.status == '0') {
								item.status = '1'
							} else {
								item.status = '0'
							}
							console.log("用户点了取消2:" + item.status)
						}
					},
				})
			},
			checkPermi,
			checkRole,
			addressSourceChange(n) {
				console.log('addressSourceChange', n);
				this.setMeal.addressSource = n;
			},
			//整个页面底部
			onReachBottom() {
				console.log('到达底部333')
			},
			//整个页面底部
			onReachBottom() {
				console.log('到达底部333')
			},
			//只是list这个区域的到达底部
			scrolltolower() {
				console.log('到底部了翻页')
				if (this.setMeal.pageNum >= this.setMeal.pageTotal) {
					uni.$u.toast('没有更多数据!');
				} else {
					this.setMeal.pageNum = this.setMeal.pageNum + 1;
					this.getPageList(2);
				}
			},
			sectionChange(index) {
				let oldCurNow = this.curNow;
				this.curNow = index;
				if (index === 0 && oldCurNow === 1) {
					uni.redirectTo({
						url: '/pages/setMeal/setMeal'
					})
				}
			},

			rules: {
				'nickName': [{
					type: 'string',
					required: false,
					max: 8,
					message: '老板姓名',
					trigger: ['blur', 'change']
				}],
				'userName': [{
					type: 'number',
					required: false,
					message: '请输入11位手机号',
					trigger: ['blur', 'change']
				}],
				'createTimeStart': [{
					type: 'string',
					required: false,

					message: '点击选择时间',
					trigger: ['blur', 'change']
				}],

				'createTimeEnd': [{
					type: 'string',
					required: false,
					message: '点击选择时间',
					trigger: ['blur', 'change']
				}],
			},

			// 打开picker
			openDatetimePicker() {
				this.$refs.myPicker.show();
			},

			// 关闭picker
			closeDatetimePicker() {
				this.$refs.myPicker.hide();
			},

			openDatetimePicker2() {
				this.$refs.myPicker2.show();
			},

			// 关闭picker
			closeDatetimePicker2() {
				this.$refs.myPicker2.hide();
			},

			createTimeStart(e) {
				console.log(e);
				// {year: "2023", month: "07", day: "11", hour: "15", minute: "21", seconds: '55'}
				this.setMeal.params.beginTime = `${e.year}-${e.month}-${e.day}`;
			},
			createTimeEnd(e) {
				console.log(e);
				// {year: "2023", month: "07", day: "11", hour: "15", minute: "21", seconds: '55'}
				this.setMeal.params.endTime = `${e.year}-${e.month}-${e.day}`;
			},
			resetsetMeal() {
				this.dataLists = [];
				this.setMeal.pageNum = 1,
					this.setMeal.pageSize = 5,
					this.setMeal.pageTotal = 1
			},
			async getPageList(tag) {
				try {
					if (tag === 1) {
						this.resetsetMeal();
					}
					const res = await this.dateValidate();
					console.log('res' + res);
					console.log('res' + typeof res);
					if (!res) {
						console.log('数据校验失败return')
						return;
					}
					const res2 = await listMeal(this.setMeal);

					console.log(JSON.stringify(res2));
					this.dataLists.push(...res2.rows);
					this.setMeal.pageTotal = Math.ceil(res2.total / this.setMeal.pageSize);
				} catch (error) {
					console.error('发生错误:', error);
				}
			},
			myUptate(itme) {
				console.log(JSON.stringify(itme))
				updateMeal(itme).then(response => {
					this.$modal.msgSuccess("修改成功");
					this.getPageList(1);
				});
			},

			myDelete(itme) {
				console.log(JSON.stringify(itme))
				this.$modal.confirm('是否确认删除用户编号为"' + itme.id + '"的数据项？').then(function() {
					return delMeal(itme.id);
				}).then(() => {
					this.getPageList(1);
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {
					this.$modal.msgError('删除失败')
				});
			},

			dateValidate() {
				return new Promise((resolve, reject) => {
					let tag = true;
					this.$refs.uForm.validate().then(res => {
						if (this.setMeal.params.beginTime != '' && this.setMeal.params
							.beginTime !=
							null && this.setMeal.params.beginTime != undefined) {
							if (!validateDate(this.setMeal.params.beginTime)) {
								tag = false;
								uni.$u.toast('开始日期格式不对');
							}
						}
						if (this.setMeal.params.endTime != '' && this.setMeal.params
							.endTime != null &&
							this.setMeal.params.endTime != undefined) {
							if (!validateDate(this.setMeal.params.endTime)) {
								uni.$u.toast('结束日期格式不对');
								tag = false;
							}
							if (this.setMeal.params.beginTime == '') {
								uni.$u.toast('开始日期也必须选择');
								tag = false;
							}
						}
						if (tag) {
							resolve(true);
						} else {
							resolve(false);
						}
					}).catch(errors => {
						console.log('Validation errors:' + errors);
						uni.$u.toast('校验失败11111111' + JSON.stringify(errors));
						resolve(false); // 这里也返回 false
					});
				});
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		//width: 94%;
		padding: 12px;
		display: flex;
		flex-direction: column;
		margin: auto;
		background: linear-gradient(180deg, #f0f0f0 0%, #d0eaff 100%);
		height: 100vh;
	}

	.updateMessage {
		display: flex;
		justify-content: right;
		height: 40px;
		align-items: center;

		.mybuttom {
			margin-right: 10px;
		}

	}


	.box {
		background-color: #ffffff;
		/* 背景颜色 */
		border-radius: 8px;
		/* 圆角 */
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		/* 阴影效果 */
		padding: 4px;
		/* 内边距 */
		margin-top: 8px;
		/* 外边距 */
		transition: box-shadow 0.3s;
		/* 动画效果 */
	}

	.box:hover {
		box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
		/* 增强阴影 */
	}

	.u-list {
		max-height: 400px;
		/* 设置最大高度 */
		overflow-y: auto;
		/* 允许垂直滚动 */
	}

	.myMeal1 {
		display: flex;
		justify-content: left;
	}
</style>